import request from '@/utils/request'
import requestFile from '@/utils/request-file'
import Qs from 'qs'
import ObjectUtil from './object-util'
const initQueryObj = { list: [], page: 0, limit: 10, loading: false, hasMore: true, isEmpty: false, pages: 1, total: 0 }
export default class RequestHelper {
  moduleUrl='';
  static getCommonFunc() {
    return {
      getInitQueryList: function(count) {
        const pStr = JSON.stringify(initQueryObj)
        if (ObjectUtil.isNull(count) || count === 1) {
          return JSON.parse(pStr)
        } else {
          const pArr = []
          ObjectUtil.getRange(0, count).forEach(i => {
            pArr.push(JSON.parse(pStr))
          })
          return pArr
        }
      }
    }
  }

  constructor(moduleUrl) {
    this.moduleUrl = moduleUrl
    // console.log('this', this)
    return this
  }
  _baseMethod(url, method, params, headers) {
    let data = {
      url: url,
      headers: headers,
      method: method
    }

    if (method === 'get') {
      data = {
        ...data,
        params: params,
        paramsSerializer: function(params) {
          return Qs.stringify(params, { arrayFormat: 'repeat' })
        }
      }
    } else if (method === 'post') {
      data = {
        ...data,
        data: params
      }
    }
    return request(data)
  }
  file(apiUrl) {
    console.log(apiUrl)
    // 这里要用到当前RequestHelper对象的this参数，所以要用lambada格式
    return function(params) {
      return requestFile({
        url: apiUrl,
        method: 'get',
        params: params,
        responseType: 'arraybuffer',
        paramsSerializer: function(params) {
          return Qs.stringify(params, { arrayFormat: 'repeat' })
        }
      })
    }
  }
  get(apiUrl, hasHeader = false) {
    const method = 'get'
    const baseMethod = this._baseMethod
    // console.log(baseMethod,'baseMethod')
    const moduleUrl = this.moduleUrl
    if (hasHeader) {
      return function() {
        return function(params, headers) {
          return baseMethod(
            moduleUrl + apiUrl,
            method,
            params,
            headers)
        }
      }
    } else {
      return function(params) {
        return baseMethod(
          moduleUrl + apiUrl,
          method,
          params)
      }
    }
  }

  post(apiUrl, hasHeader = false) {
    const method = 'post'
    const moduleUrl = this.moduleUrl
    const baseMethod = this._baseMethod
    if (hasHeader) {
      return function() {
        return function(params, headers) {
          return baseMethod(
            moduleUrl + apiUrl,
            method,
            params,
            headers)
        }
      }
    } else {
      return function(params) {
        return baseMethod(
          moduleUrl + apiUrl,
          method,
          params)
      }
    }
  }
}
